package o2o.web.actions.postman;

import com.jinyou.utils.common.*;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.postman.PostmanPositionMemory;
import o2o.cache.sys.SysConfigDepositMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.wallet.UserWalletMemory;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.order.OrderInfo;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.postman.PostmanPositionInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.UserWallet;
import o2o.dao.VO.postman.CityPostmanVO;
import o2o.service.delivery.to.DeliveryOrderStateTO;
import o2o.service.order.shop.ShopOrderService;
import o2o.system.data.PROMPTS;
import o2o.system.data.SYS_SETTINGS;
import o2o.utils.MultilingualResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

//配送员位置管理
@Controller
public class PostmanPositionController {
    //-------------------------------------------------------配送员位置信息
    //配送员位置更新
    @RequestMapping(method = RequestMethod.POST, value = "/postman/position/report")
    @ResponseBody
    public String postman_position(String token, Double lat, Double lng, String city, String address) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(user.getUsername());
        if (null == cityPostman) {
            return AjaxResult.errorResult("未查询到配送员信息");
        }

        if (ValidateUtil.isNotNull(city)) {
            city = SysCommon.removeShi(city);
        }

        //更新配送员位置信息
        PostmanMan.updatePostmanPosition(cityPostman.getId(), cityPostman.getUsername(), lat, lng, city, address);

        return AjaxResult.successResult();
    }

    //获取配送员的最新位置
    @RequestMapping(method = RequestMethod.POST, value = "/postman/position/get")
    @ResponseBody
    public String get_postman_position(String token, String sysAppKey, String orderNo, String postmanUsername, String lang) {
        //验证用户有效性
//        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
//        if (user == null) {
//            return AjaxResult.errorLogoutResult();
//        }
        // 第三方配送的话  直接去查配送
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (orderInfo != null && orderInfo.getIsOtherPost() == 1) {
            // 哒哒配送的话 直接去访问哒哒
            DeliveryOrderStateTO orderStateTO = ShopOrderService.getInstance().queryDeliveryOrderState(sysAppKey, orderNo);
            PostmanPositionInfo info = null;
            if (orderStateTO != null && ValidateUtil.isLatLng(orderStateTO.getCurrDeliveLat(), orderStateTO.getCurrDeliveLng())) {
                info = new PostmanPositionInfo();
                info.setPostmanUsername(info.getPostmanUsername());
                info.setLat(orderStateTO.getCurrDeliveLat());
                info.setLng(orderStateTO.getCurrDeliveLng());
            }
            return AjaxResult.successResult(info);
        }
        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(postmanUsername);
        if (null == cityPostman) {
//            return AjaxResult.errorResult("当前配送员不存在，请查证");
            return MultilingualResult.errorResultV2(PROMPTS.DISTRIBUTOR_NOT_EXIST, lang);
        }
        PostmanPositionInfo info = PostmanPositionMemory.getInstance().get(cityPostman.getId());

        return AjaxResult.successResult(info);
    }

    //获取配送员的最新位置  管理员
    @RequestMapping(method = RequestMethod.POST, value = "/admin/postman/position/get")
    @ResponseBody
    public String get_postman_position_full(String token, String postmanUsername) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(postmanUsername);
        if (null == cityPostman) {
            return AjaxResult.errorResult("当前配送员不存在，请查证");
        }
        PostmanPositionInfo info = PostmanPositionMemory.getInstance().get(cityPostman.getId());

        if (null != info) {
            Integer count = OrderInfoMemory.getInstance().countOfDeliveryIng(postmanUsername);
            if (ValidateUtil.isAbsInteger(count)) {
                info.setOrderCount(count);
            }
        }

        return AjaxResult.successResult(info);
    }


    //-------------------------------用户端获取附近骑手
    //获取配送员列表及对应的位置
    @RequestMapping(method = RequestMethod.POST, value = "/user/city/postman/position/list")
    @ResponseBody
    public String user_city_postman_list(String token,
                                         String city, String province, String county, String region,
                                         String username, String name,
                                         Double lat, Double lng,
                                         Integer page, Integer size) {
        //验证用户有效性
//        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
//        if (user == null) {
//            return AjaxResult.errorLogoutResult();
//        }

        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("市不能为空");
        }

//        List<CityPostman> list = CityPostmanMemory.getInstance().listOfCity(city, 2);//2全部
        List<CityPostman> list = CityPostmanMemory.getInstance().listOfCity(city, 2, null, null, null, null, null, null);//2全部
        if (ValidateUtil.isAbsList(list)) {
            List<CityPostmanVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                CityPostman cityPostman = list.get(i);
                if (null == cityPostman) {
                    continue;
                }

                //认证
                if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY
                        && (null == cityPostman.getIsVerify() || 0 != 1 - cityPostman.getIsVerify())) {
                    continue;
                }
                if (null != SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_VERIFY_FACE) {
                    UserInfo postmanUser = UserInfoMemory.getInstance().getUserInfo(cityPostman.getUsername());
                    if (null != postmanUser && null != postmanUser.getIsCert() && 0 == 1 - postmanUser.getIsCert()) {
                        //已认证
                    } else {
                        continue;
                    }
                }

                //押金
                if (null != SYS_SETTINGS.POSTMAN_MUST_DEPOSIT && 0 == 1 - SYS_SETTINGS.POSTMAN_MUST_DEPOSIT) {
                    // 必须缴纳
                    //验证押金金额是否满足
                    UserWallet userWallet = UserWalletMemory.getInstance().getWallet(cityPostman.getUsername());
                    if (null == userWallet) {
                        continue;
                    }
                    if (null == userWallet.getDepositMoney() || userWallet.getDepositMoney() <= 0) {
                        continue;
                    }
                    //必须缴纳的押金金额
                    Double money = SysConfigDepositMemory.getInstance().getByType(UserType.POSTMAN);
                    if (null == money) {
                        money = 0d;
                    }

                    if (JYMathDoubleUtils.sub(userWallet.getDepositMoney(), money) < 0) {
                        continue;
                    }
                }

                CityPostmanVO vo = PostmanMan.getOne(cityPostman);
                if (null == vo) {
                    continue;
                }


                if (ValidateUtil.isNotNull(username) && !vo.getUsername().equals(username)) {
                    continue;
                }
                if (ValidateUtil.isNotNull(name) && !vo.getName().equals(name)) {
                    continue;
                }

                //获取配送员位置信息
                PostmanPositionInfo info = PostmanPositionMemory.getInstance().get(vo.getId());
                if (null != info) {
                    Integer count = OrderInfoMemory.getInstance().countOfDeliveryIng(vo.getUsername());
                    if (ValidateUtil.isAbsInteger(count)) {
                        info.setOrderCount(count);
                    }

//                    //距离
//                    if (ValidateUtil.isAbsDouble(lat) && ValidateUtil.isAbsDouble(lng)
//                            && ValidateUtil.isAbsDouble(info.getLat()) && ValidateUtil.isAbsDouble(info.getLng())) {
//                        Double distinct = Geohash.distance(lat, lng, info.getLat(), info.getLng());
//                        if (ValidateUtil.isNotAbsDouble(distinct)) {
//                            vo.setDistinct(distinct);
//                        }
//                    }
                    //距离
                    if (ValidateUtil.isLatLng(lat, lng)
                            && ValidateUtil.isLatLng(info.getLat(), info.getLng())) {
                        Double distinct = Geohash.distance(lat, lng, info.getLat(), info.getLng());
                        if (ValidateUtil.isNotAbsDouble(distinct)) {
                            vo.setDistinct(distinct);
                        }
                    }


                }

                vo.setPositionInfo(info);//配送员所在的位置

                voList.add(vo);
            }

            if (ValidateUtil.isAbsList(voList)) {
                Collections.sort(voList, new Comparator<CityPostmanVO>() {
                    // 先按距离升序，序号相同 则空闲升序
                    public int compare(CityPostmanVO arg0, CityPostmanVO arg1) {
                        if (arg1.getDistinct().compareTo(arg0.getDistinct()) == 0) {
                            return arg1.getDistinct().compareTo(arg0.getDistinct()) > 0 ? 1 : -1;
                        } else {
                            return (int) (arg0.getPositionInfo().getOrderCount() - arg1.getPositionInfo().getOrderCount());
                        }
                    }
                });
            }

            JYPageUtils.PageList pageList = JYPageUtils.getList(voList, page, size);
            if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
                return AjaxResult.successResult(pageList.totalCount, pageList.list.size(), pageList.list);
            }
//
//            JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
//            if (null != pageList && ValidateUtil.isAbsList(pageList.list)) {
//                List<CityPostmanVO> voList = new ArrayList<>();
//                for (int i = 0; i < pageList.list.size(); i++) {
//                    if (null == pageList.list.get(i)) {
//                        continue;
//                    }
//                    CityPostmanVO vo = addOne((CityPostman) pageList.list.get(i));
//                    if (null == vo) {
//                        continue;
//                    }
//
//
//                    PostmanPositionInfo info = PostmanPositionMemory.getInstance().get(vo.getId());
//                    if (null != info) {
//                        Integer count = OrderInfoMemory.getInstance().countOfDeliveryIng(vo.getUsername());
//                        if (ValidateUtil.isAbsInteger(count)) {
//                            info.setOrderCount(count);
//                        }
//                    }
//
//                    if (ValidateUtil.isAbsDouble(lat) && ValidateUtil.isAbsDouble(lng)
//                            && ValidateUtil.isAbsDouble(info.getLat()) && ValidateUtil.isAbsDouble(info.getLng())) {
//                        Double distinct = Geohash.distance(lat, lng, info.getLat(), info.getLng());
//                        if (ValidateUtil.isNotAbsDouble(distinct)) {
//                            vo.setDistinct(distinct);
//                        }
//                    }
//
//                    vo.setPositionInfo(info);//配送员所在的位置
//
//                    voList.add(vo);
//                }
//
//                if (ValidateUtil.isAbsList(voList)) {
//                    Collections.sort(voList, new Comparator<CityPostmanVO>() {
//                        // 先按距离升序，序号相同 则空闲升序
//                        public int compare(CityPostmanVO arg0, CityPostmanVO arg1) {
//                            if (arg0.getDistinct().compareTo(arg1.getDistinct()) == 0) {
//                                return arg0.getDistinct().compareTo(arg1.getDistinct()) > 0 ? 1 : -1;
//                            } else {
//                                return (int) (arg0.getPositionInfo().getOrderCount() - arg1.getPositionInfo().getOrderCount());
//                            }
//                        }
//                    });
//                }
//
//                return AjaxResult.successResult(list.size(), voList.size(), voList);
//            }
        }


        return AjaxResult.successResult(0, 0, null);
    }

}
